package ajakuulauku;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;

/**
 * Entry point for the game. Coordinates further action.
 *
 */
public class Main {
	private static String [] levels;
	private static MainMenu menu;
	private static final int INTERVAL = 15;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Ball test = new Ball();
		System.out.println(test.getClass().getName());
		startGame();
	}
	
	/**
	 * Starts and restarts the game by loading the main menu.
	 */
	public static void startGame() {
	   // read levels from folder
      getLevels();
      
      // create menu
      menu = new MainMenu(levels);
      
      // get user action
      MainMenu.UserChoice choice = menu.init();
      
      // act upon user choice
      reactToUser(choice);
	}
	
	/**
	 * Reads levels from folder. Only .xml files are considered levels.
	 * 
	 */
	private static void getLevels() {
		// read levels from folder
		File levelfolder = new File("levels");
		levels = levelfolder.list(new FilenameFilter() {
	           public boolean accept(File dir, String name) {
	                return name.toLowerCase().endsWith(".xml");
	                }
	           }
	        );
		if (levels == null)
			levels = new String[0];
		Arrays.sort(levels);
	}
	
	/**
	 * Fulfills the user's request from main menu.
	 * @param choice button user clicked in main menu
	 */
	private static void reactToUser(MainMenu.UserChoice choice) {
		int levelIndex;
		String chosenLevel;
		Editor editor;
		switch (choice) {
			case Play:
				levelIndex = menu.getLevelIndex();
				chosenLevel = levels[levelIndex];
				CurrentLevel.envalue(chosenLevel);
				Game currentGame = new Game();
				currentGame.schedule(INTERVAL);
				break;
			case Cancel:
				menu.dispose();
				System.exit(0);
				break;
			case Edit:
				levelIndex = menu.getLevelIndex();
				chosenLevel = levels[levelIndex];
				XMLReader reader = new XMLReader(chosenLevel);
				System.exit(0);
				CurrentLevel.envalue(chosenLevel);
				editor = new Editor();
				editor.schedule(INTERVAL);
				break;
			case Create:
				editor = new Editor();
				editor.schedule(INTERVAL);
				break;
		}
	}

}
